const axios = require('axios');
const fs = require('fs-extra');
const ipGetter = require('./ipv4Getter');
const exec = require('child_process').exec;
const dns = require('./aliyun-dns');
const { log, error } = require('console');
const ipPath = `${__dirname}/lucky.json`;
// const {saveFile} = require('./oss');
const checkApi = 'http://gepik.top:5000';

function getEncodeIp (ip) {
  return JSON.stringify({
    ip,
  })
}

// 获取当前公网ip，30分钟轮询一次
function getPublicIp() {
  ipGetter().then((ip) => {
    console.log('获取到公网ip：'+ip);
    const prevIp = getPrevIp();
    console.log('上一次的公网ip：'+prevIp);
    const encodeIp = getEncodeIp(ip);
    if (!prevIp) {
      fs.outputFile(ipPath, encodeIp);
    }
    if (ip !== prevIp) {
      console.info('ip变更为:'+ip);
      remoteNotice('ip变更为'+ip)
      // 更新解析记录
      dns.updateRecordIp(ip).then(() => {
        fs.outputFileSync(ipPath, encodeIp);
        pushRemote(ip)
      });
      
    } else {
      console.log('公网ip未发生变化');
    }
  },error=>{
    console.error('未获取到公网ip');
  });
}
function pushRemote(ip) {
  exec('cd /volume1/share/workspace/some-tools \&\& git add .', (error, stdout, stderr) => {
    if(!error) {
      console.log('git add 成功');
      exec(`cd /volume1/share/workspace/some-tools \&\&  git commit -m"update ip ${ip}"`, (error, stdout, stderr) => {
        if(!error) {
          console.log('git commit 成功');
          exec('cd /volume1/share/workspace/some-tools \&\&  git push', (error, stdout, stderr) => {
            if(error) {
              console.log('git push 失败',error);
              console.log('强制推送')
              exec('cd /volume1/share/workspace/some-tools \&\&  git push -f',error=>{
                if(error) {
                  console.log('强制推送失败',error);
                  remoteNotice('强制推送失败')
                } else {
                  console.log('强制推送成功');
                }
              })
            }else {
              console.log('git push 成功');
            }
          });
        } else {
          console.log('git commit 失败',error);
          remoteNotice('commit失败')
          
        }
    });
    } else {
      console.log('git add 失败',error);
      
    }

})
}

function remoteNotice(content) {
  axios.get(`http://127.0.0.1:8018/fVZsYPf38WtkPtw9cTenY5/解析dns/${content}`)
}

// 获取上一次的ip
function getPrevIp() {
  if (fs.existsSync(ipPath)) {
    const prevIp = fs.readFileSync(ipPath, { encoding: 'utf-8' });
    return JSON.parse(decodeURIComponent(prevIp)).ip;
  }
  return '';
}

/**
 * @method 检查域名
 * @desc 检查当前域名解析是否正确，不正确则重新获取公网ip，ip变化则更新ip
 * @desc 接口3分钟轮询一次
 */
function checkDomainSuccess() {
  axios.get(checkApi, { timeout: 3000 }).then(
    (res) => {
      if (!res || !res.data) {
        getPublicIp();
      } else {
        console.log('域名解析正常');
      }
    },
    (error) => {
      getPublicIp();
    },
  );
}
try {
  checkDomainSuccess();
} catch (error) {
  console.log(error);
  
}

module.exports = {
  pushRemote,
  getEncodeIp,
}
